package com.demo1209.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

@WebServlet("/download.do")
public class DownLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String fileName = req.getParameter("fileName");
        String mimeType = this.getServletContext().getMimeType(fileName);
        resp.setHeader("Content-Type",mimeType );
        resp.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"),"iso-8859-1"));
        String path="http://localhost:8080/1209/upload/"+fileName;
        URL url = new URL(path);
        InputStream fis = url.openStream();


//        String path="F:\\train\\二阶段\\1207\\胡建鹏\\bookStore\\img\\"+fileName;
//        FileInputStream fis = new FileInputStream(path);
        ServletOutputStream os = resp.getOutputStream();
        int length=0;
        byte[] buffer=new byte[1024];
        while ((length=fis.read(buffer))!=0){
            os.write(buffer,0,length);
            os.flush();
        }
        fis.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
